import { ProFieldFC } from '@ant-design/pro-components';
import lodash from 'lodash';
import React from 'react';
import SfwCodeEditor from '../../../form/SfwCodeEditor';

const codeFormat = (value: any) => {
  try {
    if (typeof value === 'object') {
      if (value?.props) {
        // 当使用 "copyable": true, 取值方式
        return value?.props?.children || '';
      }
      return JSON.stringify(value, null, 2);
    }
  } catch (error) {
    return value;
  }
  return value;
};

/**
 * 代码片段组件 这个组件为了显示简单的配置，复杂的请使用更加重型的组件
 */
const FieldSfwModelShowView: ProFieldFC<{
  text: any;
  // language?: 'json' | 'text';
}> = (props, ref) => {
  const { text, mode, fieldProps } = props;
  const { value, onChange } = fieldProps;
  // const defaultValueCode = lodash.isString(defaultValue)
  //   ? defaultValue
  //   : codeFormat(defaultValue);
  const valueCode = lodash.isString(value) ? value : codeFormat(value);

  if (mode === 'read') {
    const code = codeFormat(text);
    return (
      <SfwCodeEditor ref={ref} {...fieldProps} value={code} readOnly>
        {text}
      </SfwCodeEditor>
    );
  }
  if (mode === 'edit' || mode === 'update') {
    const handleChange = (changedValue?: string) => {
      let v;
      try {
        if (lodash.isString(value)) {
          v = changedValue;
        } else {
          if (changedValue) {
            v = JSON.parse(changedValue);
          }
        }
      } catch {
        v = changedValue;
      }
      onChange(v);
    };

    return (
      <SfwCodeEditor
        ref={ref}
        {...fieldProps}
        value={valueCode}
        // defaultValue={defaultValueCode}
        onChange={(changedValue) => handleChange(changedValue)}
      />
    );
  }
  return null;
};

export default React.forwardRef(FieldSfwModelShowView);
